package leung.website.sample

import io.ktor.application.Application
import io.ktor.application.ApplicationCall
import io.ktor.application.call
import io.ktor.application.install
import io.ktor.features.HttpsRedirect
import io.ktor.html.respondHtml
import io.ktor.http.ContentType
import io.ktor.response.respondRedirect
import io.ktor.response.respondText
import io.ktor.routing.get
import io.ktor.routing.routing
import io.ktor.server.engine.applicationEngineEnvironment
import io.ktor.server.engine.connector
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import kotlinx.css.*
import kotlinx.html.*

fun main() {
    val aEE = applicationEngineEnvironment {
        connector {
            host = System.getenv("HOST") ?: "localhost"
            port = System.getenv("PORT")?.toInt() ?: 80
        }
        modules.add(Application::main)
        watchPaths = listOf("build/classes")
    }
    embeddedServer(Netty, aEE).start(wait = true)
}

fun Application.main() {
    //install(HttpsRedirect)
    routing {
        // Default page
        get {
            call.respondRedirect("index.html")
        }
        // Main page
        get("index.html") {
            call.respondHtml {
                head {
                    lang = "en"
                    styleLink("style/app.css")
                }
                body {
                    h1 {
                        +"Hello World"
                    }
                }
            }
        }
        // CSS
        get("style/app.css") {
            call.respondCss {
                kotlinx.css.h1 {
                    color = Color.red
                }
            }
        }
    }
}

suspend inline fun ApplicationCall.respondCss(builder: CSSBuilder.() -> Unit) {
    respondText(CSSBuilder().apply(builder).toString(), ContentType.Text.CSS)
}